package si.cir.gui;

import java.util.ArrayList;
import java.util.List;

import si.cir.R;
import si.cir.entities.Stuk;
import si.cir.util.WSclient;
import android.app.ListFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class StukListFragment extends ListFragment {
	
	private List<Stuk> novice;
	
	private Runnable getStukiBackgroundThread = new Runnable() {
		public void run() {
			getStukiInBackgroundThread();
		}
	};

	private void getStukiInBackgroundThread() {
		novice = WSclient.getProgram();
		if(novice != null){
			final List<String> imena = new ArrayList<String>();
			for(Stuk novica : novice)
				imena.add(novica.getIme());
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.simple_item, imena));
					setListShown(true);
				}
			});
		}else{
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(getActivity(), "V tej kategoriji ni objav",
						Toast.LENGTH_LONG).show();
					getActivity().finish();
				}
			});
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListShown(false);

		Thread thread = new Thread(null, getStukiBackgroundThread, "Background");
		thread.start();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(novice.get(position).getPovezava()));
		startActivity(intent);
	}
}
